package com.fool
{
	import mx.collections.ArrayCollection;

	public class Deck implements ISerializable
	{
		
		[Bindable]
		public var source:ArrayCollection = new ArrayCollection();
		
		public function Deck()
		{
			var cards:Array = getDeckOfCards();
			source = new ArrayCollection( shuffle(cards) );
		}
		
		public function getTrumpCard():Card
		{
			return source.getItemAt( count - 1) as Card; //ruby: last
		}
		
		public function invalidate():void
		{
			function setValuesForEachCards(item:*, index:int, array:Array):void 
			{
				var card:SimpleCard = item as SimpleCard;
				card.isTrump = (card.suit == getTrumpCard().suit)
			}
			
			var cards:Array = source.source;
			cards.forEach(setValuesForEachCards);			
		}

		public function get count():uint
		{
			return source.length;
		}
		
		public function getCards(count:uint):Array
		{
			var result:Array = [];
			while( count > 0 && !empty )
			{
				count--;
				result.push( source.removeItemAt(0) ); //Ruby shift()
			}
			return result;
		}
		
		public function get empty():Boolean
		{
			return source.length == 0;
		}
				
		private function shuffle(cards:Array):Array
		{
			var result:Array = [];
			while(cards.length)
			{
				var position:uint = int( Math.random() * cards.length);
				var deletedItems:Array = cards.splice(position,1);
				result.push( deletedItems[0] );
			}
			return result
		}
		
		private  function getDeckOfCards():Array
		{
			var result:Array = [];
			for (var i:int = 0; i < 9; i++) 
			{
				for (var j:int = 0; j < 4; j++) 
				{
					result.push(new Card(i, j)); 		
				}
			}
			return result;
		}

		public function deSerialize(value:String):void
		{
			var arr:Array = value.split(Enum.SEQUENCE_DELIMITER);
			source = new ArrayCollection
		}
		
		public function serialize():String
		{
			return source.source.join(Enum.SEQUENCE_DELIMITER);
		}
		
	}
}